package com.dtsz.m2.utils;


import android.os.Build;
import android.util.Base64;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;

import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.logging.Logger;

import javax.crypto.Cipher;

public class RSAEncrypt {
    //
    static final String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC2YXpeSfyh/W3I4lnLT/mDUYvwc8Z1WaJvrJapkfSVS2ZnkaWI3sW2GqH4FFlrsgt7Yx+RGmvac/3Fcyt3FBVLwYIv8Imhdxc/cyNV3aD+jFbyyIBS1ulK+g/Y6lIbwXwsDnB+mp0RcZUJEIp6ZL0waoirl5cEW5KpUaaL/+Lx9wIDAQAB";
    private static final Logger logger = Logger.getLogger("RSAEncrypt");

    /**
     * 加密请请求头文件
     *
     * @param timestampStr
     * @return
     */

    public static String md5Hander(Long timestampStr) {
        String sign2 = new String(Hex.encodeHex(DigestUtils.md5(timestampStr + RSAEncrypt.publicKey)));
        sign2 = new String(Hex.encodeHex(DigestUtils.md5(sign2)));
        //校验签名是否正确？
        return sign2;
    }

    //参数一：需要加密的文本  参数二:加密的公钥
    public static String encrypt(String text) {
        try {
            // Base64为android util包自带的，publicKeyString是服务器获取的公钥字符串，参数选择NO_WRAP
            byte[] keyByte = Base64.decode(publicKey.getBytes(), Base64.NO_WRAP);
            // 获取keyspec （java.security.spec.X509EncodedKeySpec）
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyByte);
            // 获取keyfactory （java.security.KeyFactory）
            KeyFactory keyFactory;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                //适配Android P及以后版本，否则报错NoSuchAlgorithmException
                keyFactory = KeyFactory.getInstance("RSA");
            } else {
                keyFactory = KeyFactory.getInstance("RSA", "BC");
            }
            // 获取公钥 （java.security.PublicKey）
            PublicKey publicKey = keyFactory.generatePublic(keySpec);
            // 初始化加密类
            Cipher cipher = null;
            cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            // 加密后获取字节数组 text为要加密的字符串
            byte[] enBytes = cipher.doFinal(text.getBytes());
            // 加密结果再做一次编码，获取的字符串作为密文传给服务器验证
            return Base64.encodeToString(enBytes, Base64.NO_WRAP);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
